package com.example.juc.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {

    public static void main(String[] args) {
        C c = new C();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                c.increment();
            }
        }, "1").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                c.decrement();
            }
        }, "2").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                c.decrement1();
            }
        }, "3").start();
    }

}

class C {

    private int num = 1;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();

    public void increment() {
        lock.lock();

        try {
            while (num != 1) {
                condition.await();
            }
            num++;
            System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
            condition1.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();

        try {
            while (num != 2) {
                condition1.await();
            }
            num++;
            System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
            condition2.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void decrement1() {
        lock.lock();

        try {
            while (num != 3) {
                condition2.await();
            }
            num=1;
            System.out.println("线程：" + Thread.currentThread().getName() + "，num===>" + num);
            condition.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
